<?php

class UserFavorite extends UsersAppModel
{
    var $name = 'UserFavorite';
	
	
	function beforeSave()
	{
		$record = $this->data['UserFavorite'];

		// check for duplication
		if($this->find(array('UserFavorite.user_id'=>$record['user_id'], 'UserFavorite.item_id'=>$record['item_id'], 'UserFavorite.type'=>$record['type'])))
		{
			return false;
		}
		
		return true;
	}

	function getFans($user_id, $type, $limit=null)
	{ 
		$favoriteIds = array();
		$favItems = $this->findAllByitem_id($user_id,null,'UserFavorite.added desc', $limit);
		foreach($favItems as $favItem)
		{
			$favoriteIds[]=$favItem['UserFavorite']['user_id'];
		}

		return $favoriteIds;
	}

	function getFavorite($user_id, $type, $limit=null)
	{
		$favoriteIds = array();
		$favItems = $this->findAllByuser_id($user_id,null,'UserFavorite.added desc', $limit);
		foreach($favItems as $favItem)
		{
			$favoriteIds[]=$favItem['UserFavorite']['item_id'];
		}

		return $favoriteIds;
	}	

	function getFavCount($type='all',$userIds=null)
	{
		if($userIds==null)
		{
			$conditions = array('UserFavorite.type'=>$type);
		}else
		{
			$conditions = array('UserFavorite.type'=>$type,'UserFavorite.user_id'=>$userIds);
		}		
		$data = $this->find('all',array('fields'=>array('UserFavorite.user_id','count(item_id) as favCount'),'conditions'=>$conditions,'group'=>array('UserFavorite.user_id')));
		if($data)
		{
			$userIdAndFavCount = Set::combine($data,'{n}.UserFavorite.user_id','{n}.0.favCount');
		}
		else
			$userIdAndFavCount = null;
		return $userIdAndFavCount;		
	}

	function getFavCount_old($type='all',$userIds=null)
	{
		if($userIds==null)
		{
			$conditions = array('UserFavorite.type'=>$type);
		}else
		{
			$conditions = array('UserFavorite.type'=>$type,'UserFavorite.user_id'=>$userIds);
		}		
		$favCount = $this->find('count',array('conditions'=>$conditions));
		return $favCount;		
	}

}
?>